﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Xml.Serialization;

namespace G.Model
{
    [CollectionDataContract]
    public class GameTaskDefs : KeyedCollection<string, GameTaskDef>
    {
        public delegate void TaskHandler(GameTaskDef player);
        public delegate void TaskChangedHandler();
        
        public event TaskChangedHandler TaskRemovedEvent;
        public event TaskHandler TaskAddedEvent;
        public event TaskChangedHandler TaskChangedEvent;
        
        private GameSpaceDef _GameDef;

        public GameTaskDefs() : this(null) { }
        
        internal GameTaskDefs(GameSpaceDef pGameDef)
        {
            _GameDef = pGameDef;
        }

        [Browsable(false), IgnoreDataMember]
        public GameSpaceDef GameDef
        {
            get { return _GameDef; }
            set { _GameDef = value; }
        }

        protected override void InsertItem(int index, GameTaskDef task)
        {
            string key = task.Name;
            for (int i = 1; i < 100; i++)
            {
                if (base.Contains(task.Name))
                {
                    task.Name = key + i;
                    continue;
                }

                break;
            }
            
            task.GameDef = _GameDef;
            base.InsertItem(index, task);
            FireAddedEvent(task);
        }
        
        protected override void RemoveItem(int index)
        {
            base.RemoveItem(index);
            FireRemovedEvent();
        }

        protected override string GetKeyForItem(GameTaskDef item)
        {
            return item.Name;
        }
        
        internal void ChangeKey(GameTaskDef item, string newKey)
        {
            base.ChangeItemKey(item, newKey);
        }
            
        private void FireRemovedEvent()
        {
            if (TaskRemovedEvent != null)
            {
                TaskRemovedEvent();
            }
        }
        
        private void FireAddedEvent(GameTaskDef pGameTaskDef)
        {
            if (TaskAddedEvent != null)
            {
                TaskAddedEvent(pGameTaskDef);
            }
        }
        
        public void FireChangedEvent()
        {
            if (TaskChangedEvent != null)
            {
                TaskChangedEvent();
            }
        }
        
    }
}
